package com.cxs.entry2.slice;

import com.cxs.entry2.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.event.commonevent.CommonEventData;
import ohos.event.commonevent.CommonEventManager;
import ohos.rpc.RemoteException;

public class MainAbilitySlice extends AbilitySlice {
    static final String EVENT_ACTION = "com.cxs.commoneventtest.event";
    static final String INTENT_PARAM_KEY = "intent.param.key";

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        findComponentById(ResourceTable.Id_text_helloworld).setClickedListener(this::publishEvent);
    }

    /**
     * 发布公共事件
     * @param component
     */
    private void publishEvent(Component component) {
        // 1. 构建一个Intent对象，包含了自定义的事件的标识符
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withAction(EVENT_ACTION)     // 自定义的事件标识符
                .build();
        intent.setOperation(operation);
        intent.setParam(INTENT_PARAM_KEY, "Hello HarmonyOS");

        // 2. 构建CommonEventData对象
        CommonEventData commonEventData = new CommonEventData(intent);

        // 3. 核心的发布事件的动作
        try {
            CommonEventManager.publishCommonEvent(commonEventData);
            System.out.println("发布事件结束");
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
